/**
 * 
 */
package com.wsmhz.web.interceptor;

import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

/**
 * create by tangbj on 2018/3/25
 * 每个API都会处理的时间拦截器
 */
@Component
public class ApiTimeInterceptor implements HandlerInterceptor {

	private static Logger logger = LoggerFactory.getLogger(ApiTimeInterceptor.class);

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		logger.info("类名：{}，方法名：{}",
				((HandlerMethod)handler).getBean().getClass().getSimpleName(),((HandlerMethod)handler).getMethod().getName());
		request.setAttribute("startTime", new Date().getTime());
		return true;
	}

	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
	}

	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
		Long start = (Long) request.getAttribute("startTime");
		logger.info("ApiTimeInterceptor 耗时:"+ (new Date().getTime() - start));
	}

}
